<template>
  <div>
    <template v-for="(item, index) in options">
      <template v-if="values.includes(item.value)">
        <span
          v-if="
            item.raw.listClass && (item.raw.listClass === 'default' || item.raw.listClass === '')
          "
          :key="item.value"
          :index="index"
          :class="item.raw.cssClass"
        >
          {{ item.label + ' ' }}
        </span>
        <el-tag
          :disable-transitions="true"
          :key="item.value"
          :index="index"
          :type="item.raw.listClass === 'primary' ? '' : item.raw.listClass"
          :class="item.raw.cssClass"
        >
          {{ item.label + ' ' }}
        </el-tag>
      </template>
    </template>
    <template v-if="unmatch && showValue">
      {{ handleArray(unmatchArray) }}
    </template>
  </div>
</template>

<script lang="ts">
  export default {
    name: 'DictTag',
  }
</script>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  /*接收父组件传来的参数*/
  const props = defineProps({
    options: {
      type: Array<any>,
      required: true,
    },
    value: {
      type: [Number, String, Array],
      required: true,
    },
    //是否进行显示
    showValue: {
      type: Boolean,
      default: true,
    },
  })
  const unmatchArray = ref([]) // 记录未匹配的项

  const values = computed(() => {
    if (props.value !== null && typeof props.value !== 'undefined') {
      return Array.isArray(props.value) ? props.value : [String(props.value)]
    } else {
      return []
    }
  })

  const unmatch = computed(() => {
    unmatchArray.value = []
    if (props.value !== null && typeof props.value !== 'undefined') {
      // 传入值为非数组
      if (!Array.isArray(props.value)) {
        if (props.options.some((v) => v.value === props.value)) return false
        unmatchArray.value.push(props.value)
        return true
      }
      // 传入值为Array
      props.value.forEach((item) => {
        if (!props.options.some((v) => v.value === item)) unmatchArray.value.push(item)
      })
      return true
    }
    // 没有value不显示
    return false
  })

  function handleArray(array) {
    if (array.length === 0) return ''
    return array.reduce((pre, cur) => {
      return pre + ' ' + cur
    })
  }
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
</style>
